import React, {useEffect, useState} from 'react';
import {
    type Record,
    reqDeleteTrademark,
    reqTrademarkPageLimit,
    reqTrademarkSave,
    reqTrademarkUpdate,
} from "@/api/trademark";
import {Button, Card, Form, Input, message, Modal, Pagination, Space, Table, Tag, Upload} from "antd";
import {PlusOutlined,FormOutlined,DeleteOutlined,LoadingOutlined} from "@ant-design/icons"
import type { UploadChangeParam } from 'antd/es/upload';
import type { PaginationProps, } from 'antd';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';


function Trademark() {
    //当前页
    const [current,setCurrent] = useState(1)
    //每页条数
    const [pageSize,setPageSize] = useState(5)
    //总页树
    const [total,setTotal] = useState(0)
    //分页的数据
    const [trademarkList,setTrademarkList] = useState<Record[]>([])
    // @ts-ignore
    // @ts-ignore
    //收集Form表单中的数据
    const [id,setId] = useState(0)
    const [tmName,setTmName] = useState("")
    const [logoUrl,setLogoUrl] = useState("")


    //监听每页条数的变化
    const onShowSizeChange: PaginationProps['onShowSizeChange'] = (current, pageSize) => {
        setCurrent(current);
        setPageSize(pageSize);
        getTrademark(current,pageSize)
    };
    //
    const onChange:PaginationProps['onChange'] = (current,page)=>{
        getTrademark(current,pageSize)
    }
    const getTrademark =async (page:number,limit:number)=>{
       try {
           const result = await reqTrademarkPageLimit(page,limit);
           console.log(result)
           setTrademarkList(result.records)
           setCurrent(result.current)
           setPageSize(result.size)
           setTotal(result.total)
       }catch (e){
           return Promise.reject(e)
       }
    }

    //添加弹框
    const [open, setOpen] = useState<boolean>(false);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const AddTrade = () => {
        setId(0)
        setTmName("")
        setLogoUrl("")
        setOpen(true);
    };
    //添加或修改
    const handleOk = async () => {
        setConfirmLoading(true);
        try {
            if(id){
                await reqTrademarkUpdate({id,tmName,logoUrl})
                message.success('修改成功')
            }else {
                await reqTrademarkSave({tmName,logoUrl})
                message.success("添加成功")
            }
        }catch (e){
            return Promise.reject(e)
        }
        setOpen(false);
        getTrademark(current,pageSize);
        setConfirmLoading(false);
    };
    const handleCancel = () => {
        setOpen(false);
    };

    //图片上传逻辑
    const getBase64 = (img: RcFile, callback: (url: string) => void) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result as string));
        reader.readAsDataURL(img);
    };

        const [loading, setLoading] = useState(false);
        const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
            console.log(info)
            if (info.file.status === 'uploading') {
                setLoading(true);
                return;
            }
            if (info.file.status === 'done') {
                // Get this url from response in real world.
                getBase64(info.file.originFileObj as RcFile, (url) => {
                    setLoading(false);
                    setLogoUrl(info.file.response.data)
                });
            }
        };
        const uploadButton = (
            <div>
                {loading ? <LoadingOutlined /> : <PlusOutlined />}
                <div style={{ marginTop: 8 }}>Upload</div>
            </div>
        );
        const changeTmName = (e:any)=>{
            setTmName(e.target.value)
        }

    useEffect(()=>{
        getTrademark(current,pageSize)
    },[])
    // @ts-ignore
    // @ts-ignore
    return (
        <div>
            <Card>
                 <Button type="primary" style={{width : 80}} onClick={AddTrade}><PlusOutlined />添加</Button>
                     <Modal
                         bodyStyle={{width :400}}
                         visible={open}
                         title="添加品牌"
                         onOk={handleOk}
                         confirmLoading={confirmLoading}
                         onCancel={handleCancel}
                     >
                         <Form
                         >
                             <Form.Item label="品牌名称"  >
                                 <Input onChange={changeTmName} value={tmName} placeholder={"请输入品牌名称"}></Input>
                             </Form.Item>
                             <Form.Item label="品牌LOGO" >
                                 <Upload
                                     listType="picture-card"
                                      className="avatar-uploader"
                                     showUploadList={false}
                                     action="http://gmall-h5-api.atguigu.cn/admin/product/fileUpload"
                                     onChange={handleChange}
                                 >
                                     {logoUrl ? <img src={logoUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                                 </Upload>
                             </Form.Item>
                         </Form>
                     </Modal>
                <Table
                    pagination={false}
                    style={{marginTop:30,marginBottom:30}}
                    bordered={true}
                    rowKey={"id"}
                    columns={[
                        {
                            title: '序号',
                            align: 'center',
                            render(value,rows,index){
                                return (current-1)*pageSize + index + 1
                            }
                        },
                        {
                            title:"品牌名称",
                            align:"center",
                            dataIndex:"tmName"
                        },
                        {
                            title:"品牌LOGO",
                            align:"center",
                            render(rows){
                                return (
                                    <img width={60} height={60} src={rows.logoUrl} />
                                )
                            }
                        },
                        {
                            title:"操作",
                            render(rows){
                                return (
                                    <Space>
                                        <Button type="primary"  onClick={()=>{
                                            setId(rows.id);
                                            setTmName(rows.tmName);
                                            setLogoUrl(rows.logoUrl);
                                            setOpen(true)
                                        }}><FormOutlined />修改</Button>
                                        <Button type="primary" danger
                                        onClick={async ()=>{
                                            try {
                                                await reqDeleteTrademark(rows.id);
                                                getTrademark(current,pageSize)
                                                message.success("删除成功")
                                            }catch (e){
                                                return Promise.reject(e)
                                            }
                                        }}

                                        ><DeleteOutlined />删除</Button>
                                    </Space>
                                )
                            }
                        },

                    ]}
                    dataSource={trademarkList}
                    size="middle"
                />
                <Pagination
                    current={current}
                    pageSize={pageSize}
                    showSizeChanger
                    pageSizeOptions={["3","5","7","9"]}
                    onShowSizeChange={onShowSizeChange}
                    defaultCurrent={1}
                    onChange={onChange}
                    total={total}
                />
            </Card>
        </div>
    );
}

export default Trademark;
